<!-- 仓库设置 -->
<script setup lang="ts">
import type { TreeInstance } from 'element-plus';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DictApi, MdItemAPI, ToolTypeApi, WareStock } from '#/api';

import { nextTick, reactive, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { message, Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp, getWareStockTreeSelect } from '#/api';
import { DeleteMdItem, GetMdItem } from '#/api/mes/md/mditem';
import {
  getToolBarBtns,
  messageError,
  messageSuccess,
  PopMsg,
  setToolBarBtnDefaultDisabled,
  updateToolbarButtonStatus,
} from '#/utils';

import Aadd from './Aadd.vue';
import Add from './Add.vue';

const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};

interface Tree {
  [key: string]: any;
}
// 将字典数据添加到数组中
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
const mes_item_product = reactive<DictApi.SelectOption[]>([]);
DictResp(['sys_yes_no', 'mes_item_product']).then((res) => {
  if (res.mes_item_product) {
    mes_item_product.push(...res.mes_item_product);
  }
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

interface RowType {
  searchValue?: any;
  createBy?: string;
  createTime?: string;
  updateBy?: any;
  attr1?: any;
  attr2?: any;
  attr3?: any;
  attr4?: any;
  batchFlag?: string;
  enableFlag?: string;
  highValue?: string;
  itemCode?: string;
  itemId?: number;
  itemName?: string;
  itemOrProduct?: string;
  itemTypeCode?: string;
  itemTypeId?: number;
  itemTypeName?: string;
  maxStock?: number;
  minStock?: number;
  params?: any;
  remark?: string;
  safeStockFlag?: string;
  specification?: string;
  unitName?: string;
  unitOfMeasure?: string;
  updateTime?: any;
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'itemTypeId',
      dependencies: {
        triggerFields: ['itemTypeId'],
        show: false,
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入物料编码',
        allowClear: true,
        class: 'mr-5',
      },
      fieldName: 'itemCode',
      label: '物料编码',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入物料名称',
        allowClear: true,
      },
      fieldName: 'itemName',
      label: '物料名称',
      labelClass: '  text-[#606266] font-bold',
    },
  ],

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

// 工具栏按钮
const buttons = getToolBarBtns();
buttons.value.push(
  {
    name: '导出',
    code: 'export',
    status: 'warning',
    icon: 'vxe-icon-download',
  },
  {
    name: '导入',
    code: 'import',
    status: 'success',
    icon: 'vxe-icon-upload',
  },
);

const gridOptions: VxeGridProps<WareStock.Row> = {
  columns: [
    { align: 'left', type: 'checkbox', width: 60 },
    {
      field: 'itemCode',
      title: '物料编码',
      width: 120,
      cellRender: { name: 'CellButtonInfo', props: { onClick: onEdit } },
    },
    { field: 'itemName', title: '物料名称', width: 150 },
    { field: 'specification', title: '规格型号', width: 120 },
    { field: 'unitName', title: '单位', width: 80 },
    {
      field: 'itemOrProduct',
      title: '物料/产品',
      formatter: ({ cellValue }) => {
        const item = mes_item_product.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    { field: 'itemTypeName', title: '所属分类', width: 120 },
    {
      field: 'enableFlag',
      title: '是否启用',
      width: 150,
      slots: { default: 'enableFlag' },
    },
    {
      field: 'safeStockFlag',
      title: '安全库存',
      cellRender: { name: 'CellTag' },
    },
    {
      field: 'createTime',
      title: '创建时间',
      formatter: 'formatDateTime',
      width: 160,
    },
    {
      title: '操作',
      width: 120,
      slots: { default: 'operate' },
    },
  ],
  checkboxConfig: {
    highlight: true,
  },
  autoResize: false,
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await GetMdItem({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons: buttons.value,
  },
};

// const gridEvents: VxeGridListeners = {
//   checkboxChange() {
//     selectedRows.value = gridApi.grid.getCheckboxRecords();
//   },
// };

// 控制modal的响应式变量
const showPopup = ref(false);

/**
 * 编辑
 * @param row
 */
function onEdit(row: ToolTypeApi.Row) {
  selectedRows.value = [row];
  showPopup.value = true;
  modalApi.setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  selectedRows.value = [initData];
  showPopup.value = true;
}

/**
 * 删除
 * @param row
 */

/**
 * 删除
 * @param data 可以是单条数据或数据数组
 */
function onDelete(data: MdItemAPI.Row | MdItemAPI.Row[]) {
  const ids = Array.isArray(data)
    ? data.map((item) => item.itemId)
    : [data.itemId];

  const idString = ids.join(',');
  PopMsg(`确定要删除物料编号为【${idString}】的数据吗？`, '提示', 'warn')
    .then(() => {
      DeleteMdItem(idString)
        .then(() => {
          messageSuccess(`删除成功`);
          refreshGrid();
        })
        .catch((error) => {
          messageError(error.message || '删除失败');
        });
    })
    .catch(() => {
      // 用户点击取消
      message.info('已取消删除');
    });
}

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

// 表格事件

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    // console.warn(code);
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        onAdd();
        amodalApi.open();
        break;
      }
      case 'myDel': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      case 'myEdit': {
        // 修改逻辑
        modalApi
          .setState({
            title: '添加单位',
          })
          .open();
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
};

function refreshGrid() {
  gridApi.query();
}
const [AddModal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: Add,
});

const [AaddModel, amodalApi] = useVbenModal({
  connectedComponent: Aadd,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/* 树形控件 */
const filterText = ref('');
const treeRef = ref<TreeInstance>();

const defaultProps = {
  children: 'children',
  label: 'label',
};
const data = ref<Tree[]>([]);
getWareStockTreeSelect().then((res) => {
  data.value = res.data;
  nextTick(() => {
    treeRef.value?.filter('');
  });
});

watch(filterText, (val) => {
  // eslint-disable-next-line unicorn/no-array-callback-reference
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

function handleNodeClick(data: Tree) {
  gridApi.formApi.getValues().then((res) => {
    res.itemTypeId = data.id;
    gridApi.query(res);
  });
}
const handleEdit = (row: RowType) => {
  message.success(`打印 ${row.itemName}`);
};
</script>

<template>
  <div class="vp-raw flex w-full gap-2">
    <div class="ml-2 mt-2 w-[15%]">
      <el-input
        v-model="filterText"
        class="mb-2"
        placeholder="请输入分类名称"
      />
      <el-tree
        ref="treeRef"
        style="height: 100%"
        class="filter-tree"
        :data="data"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        node-key="id"
        highlight-current
      />
    </div>
    <div class="mt-2 w-[85%]">
      <Grid>
        <template #enableFlag="{ row }">
          <span
            class="mr-[10px]"
            :class="[{ 'blue-text': row.enableFlag === 'N' }]"
          >
            否
          </span>
          <Switch
            :checked="row.enableFlag === 'N' ? false : true"
            @change="(checked: any) => (row.enableFlag = checked ? 'Y' : 'N')"
            :aria-label="null"
          />
          <span
            class="ml-[10px]"
            :class="[
              {
                'blue-text': row.enableFlag === 'Y',
              },
            ]"
          >
            是
          </span>
        </template>
        <template #operate="{ row }">
          <VxeButton mode="text" status="primary" @click="handleEdit(row)">
            <i class="vxe-icon-print mr-1"></i>
            标签打印
          </VxeButton>
        </template>
      </Grid>
      <AddModal class="w-[850px]" title="新增物料/产品" />
      <AaddModel class="w-[850px]" title="新增物料/产品" />
    </div>
  </div>
</template>
<style scoped>
.blue-text {
  color: #1890ff;
}
</style>
